package com.guijq.codesegment.volatilelearn;

/**
 * @author yangjf
 * @version 0.1.0
 * @time 2018/11/16/016
 */
public class VolatileExample {
    private int a = 0;
    private volatile boolean flag = false;
    public void writer(){
        a = 1;          //1
        for (int i=0;i<10000;i++) {
            System.out.println(i);
        }
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        flag = true;   //2
        System.out.println("wirte end");
    }
    public void reader(){
        if(flag){      //3
            int i = a; //4
            System.out.println(i);
            System.out.println("进入 read");
        } else {
            System.out.println("read end");
        }
    }


    public static void main(String[] args) {
        VolatileExample volatileExample = new VolatileExample();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                volatileExample.writer();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                volatileExample.reader();
            }
        });

        t1.start();
        t2.start();
        volatileExample.reader();
    }

}
